const child_process = require('child_process')
const chalk = require('chalk')
const log = console.log

let process = require('process')
let notifier = require('node-notifier')

let workerProcess
let devProcess
let webpackChildProcess

let argv = require('yargs').argv
let workerProcessArgs = ['build.js', '--watch', '--novue']

function closeChildProcess(from, code) {
  log(chalk.cyan('catch err kill'))
  if (workerProcess && workerProcess.exit) {
    workerProcess.kill()
  }
  if (devProcess && devProcess.exit) {
    devProcess.kill()
  }
  if (webpackChildProcess && webpackChildProcess.exit) {
    webpackChildProcess.kill()
  }
  log('catch from ' + from)
  notifier.notify({
    title: '编译错误提示',
    message: `请重新启动编译 ${from} ${code}`
  })
  setTimeout(() => {
    process.exit()
  }, 1000)
}

if (argv.server) {
  workerProcess = child_process.exec('gulp w', {})

  workerProcess.stdout.on('data', function (data) {
    log(chalk.cyan(data))
  })

  workerProcess.stderr.on('data', function (data) {
    console.error(chalk.red(data))
  })

  workerProcess.stderr.on('close', function (data) {
    closeChildProcess('workerProcess', data)
  })

  devProcess = child_process.spawn(
    'node',
    workerProcessArgs,
    {},
  )

  devProcess.stdout.on('data', data => {
    log(chalk.blue(`${data}`))
  })

  devProcess.stderr.on('data', data => {
    log(chalk.red(`${data}`))
  })

  devProcess.on('close', code => {
    log(chalk.red(`child process exited with code ${code}`))
    closeChildProcess('devProcess', code)
  })

  webpackChildProcess = child_process.spawn(
    'node',
    ['webpack.dev.js'],
    {},
  )

  webpackChildProcess.stdout.on('data', data => {
    log(chalk.blue(`${data}`))
  })

  webpackChildProcess.stderr.on('data', data => {
    log(chalk.yellow(`${data}`))
  })

  webpackChildProcess.on('close', code => {
    log(chalk.red(`child process exited with code ${code}`))
    closeChildProcess('webpackChildProcess', code)
  })
}

if (argv.folder) {
  workerProcess = child_process.exec(`node build.js --novue --folder "${argv.folder}"`, {})

  workerProcess.stdout.on('data', function (data) {
    log(chalk.cyan(data))
  })

  workerProcess.stderr.on('data', function (data) {
    console.error(chalk.red(data))
  })
}

